//grid width and height
var bw = 200;
var bh = 400;
//padding around grid
var p = 10;
//size of canvas
var cw = bw + (p*2) + 1;
var ch = bh + (p*2) + 1;
var canvas, context, canvasObject;
var map = [];
var coordIniT1= new Coordenada(0,0);
var cellWidth=30;
var cellHeight=30;
var camposT1;
var numpisos=7;
var habporpiso=10;
var widthT=cellWidth*habporpiso;
var heightT=cellHeight*numpisos;

$(function() {
    login = $('login');
//    if (login==null){
        canvas = $('#tablero');
        canvas.attr({width: cw * 2, height: ch});
        canvasObject = canvas.get(0);
        context = canvasObject.getContext("2d");
        drawBoard();
        initialize();
        canvas.click(function(evt) {
                evt.preventDefault();
                var rect = canvasObject.getBoundingClientRect();
            var x=evt.clientX - rect.left;
                var y=evt.clientY - rect.top;
                for (var i=0;i<numpisos;i++){
                        for (var j=0;j<habporpiso;j++){
                                if (x>=camposT1[i][j].x && x<camposT1[i][j].x+cellWidth && y>=camposT1[i][j].y && y<camposT1[i][j].y+cellHeight)
                                        alert('Piso : '+(numpisos-camposT1[i][j].piso)+' hab: '+(camposT1[i][j].hab+1));
                        }
                }
        });
//    }
});

function Coordenada(x,y){
	this.x=x;
	this.y=y;
}
function CoordenadaPiso(x,y,piso,hab){
	this.x=x;
	this.y=y;
	this.piso=piso;
	this.hab=hab;
}

function drawBoard(){
	var canvas=document.getElementById("tablero");
	var context=canvas.getContext("2d");
	context.beginPath();
	//draw hotel
	context.rect(coordIniT1.x,coordIniT1.y,widthT,heightT);
	context.fillStyle="#8ED6FF";
	context.fill();
	for (i=0;i<numpisos;i++){
		context.moveTo(coordIniT1.x,coordIniT1.y+cellHeight*i);
		context.lineTo(coordIniT1.x+widthT,coordIniT1.y+cellHeight*i);
		for (j=0;j<habporpiso;j++){
			context.moveTo(coordIniT1.x+cellWidth*j,coordIniT1.y);
			context.lineTo(coordIniT1.x+cellWidth*j,coordIniT1.y+heightT);
		}
	}
	context.lineWidth=2;
	context.strokeStyle = 'red';
	context.stroke();
}
function initialize(){
	//Crear habitaciones
	//Crear las coordenadas de acuerdo a la cantidad de pisos y el numero de habitaciones por piso
	camposT1=new Array(numpisos);
	for (var i=0;i<numpisos;i++){
		camposT1[i]=new Array(habporpiso);
		for (var j=0;j<habporpiso;j++){
			camposT1[i][j]=new CoordenadaPiso(coordIniT1.y+cellHeight*j,coordIniT1.x+cellWidth*i,i,j);
		}
	}
}
/*function initMatrix(){
	if (numpisos>0 && habporpiso>0){
		for (var i=0; i<numpisos;i++){
			map[i]=[];
			for (var j=0;j<habporpiso;j++){
				map[i][j]=0;
			}
		}
		//fill the building
		for(i=0;i<numpisos;i++){
			for(j=0;j<habporpiso;j++){
				var imageObj = $(new Image());
				imageObj.load({x: cellWidth*j + (map[i][j]? 37:42), y: cellHeight*i + (map[i][j]? 53:50)}, function(e) {
					context.drawImage(this, e.data.x, e.data.y);
				}).attr('src', map[i][j]? 'img/barco.png':'img/water.png');
			}
		}
	}
}*/
/*function initMatrix(square, numNaves) {
	if(square < 2)
		return;
	var i, j, x, y;
	for(i = 0; i < square; i++) {
		map[i] = [];
		//mapOpp[i] = [];
		for(j = 0; j < square; j++){
			map[i][j] = 0;
			//mapOpp[i][j] = 0;
		}
	}
	
	for(i = 0; i < numNaves; i++) {
		var ex = false;
		do {
			x = rand(square-1);
			y = rand(square-1);
			if(map[x][y] == 0) {
				map[x][y] = 1;
				ex = true;
			}
		} while(!ex);
	}
	
	for(i = 0; i < square; i++) {
		for(j = 0; j < square; j++) {
			var imageObj = $(new Image());
			imageObj.load({x: cellWidth*j + (map[i][j]? 37:42), y: cellHeight*i + (map[i][j]? 53:50)}, function(e) {
				context.drawImage(this, e.data.x, e.data.y);
			}).attr('src', map[i][j]? 'img/barco.png':'img/water.png');
		}
	}
	
	for(i = 0; i < square; i++) {
		for(j = 0; j < square; j++) {
			var imageObj = $(new Image());
			imageObj.load({x: cellWidth*j + 177, y: cellHeight*i + 50}, function(e) {
				context.drawImage(this, e.data.x, e.data.y);
			}).attr('src', 'img/water.png');
		}
	}
			
}*/

var wsclient = (function() {
    var ws = null;
    var wsURI = 'ws://' + location.host  + '/battleship/battle';
    
    function connect(email, password) {
        if(!email || email == '' || !password || password == '') {
            return;
        }
        
        if ('WebSocket' in window) {
            ws = new WebSocket(wsURI + '?email=' + email+'?password='+password);
        } else if ('MozWebSocket' in window) {
            ws = new MozWebSocket(wsURI + '?email=' + email+'?password='+password);
        } else {
            alert('Tu navegador no soporta WebSockets');
            return;
        }
        
        ws.onopen = function () {
            setConnected(true);
        };
        
        ws.onmessage = function (event) {
            var message = JSON.parse(event.data);
            processMessage(message);
        };
        
        ws.onclose = function () {
            setConnected(false);
            document.getElementById('userName').value = '';
        };
        
        function processMessage(message) {
           if (message.messageInfo){
        	   //Respuesta del websocket
        	   serverResponse(message.messageInfo);
           } else if (message.statusInfo) {
                if (message.statusInfo.status == 'CONNECTED') {
                    addOnlineUser(message.statusInfo.user);
                } else if (message.statusInfo.status == 'DISCONNECTED') {
                    removeOnlineUser(message.statusInfo.user);
                }
            } else if (message.connectionInfo) {
                var activeUsers = message.connectionInfo.activeUsers;
                for (var i=0; i<activeUsers.length; i++) {
                    addOnlineUser(activeUsers[i]);
                }
            }
        }
    }
    
    function cleanWhitespaces(text) {
        return text.replace(/\s/g,"_");
    }
    
    function serverResponse(message){
    	/*
		 * 0 => 
		 * 1 => 
		 * 2 => 
		 * 3 => 
		 * 4 =>
		 * 5 =>
		 */
		switch (message.message){
			case 0:
				if (map[0][0]==1){
					var imageObj = $(new Image());
					imageObj.load({x: camposT1[0].x, y: camposT1[0].y}, function(e) {
						context.drawImage(this, e.data.x, e.data.y);
					}).attr('src', 'img/explosion.png');
					play(from,opponent,4);
					alert("perdiste!");
					setTimeout(function(){restartHotel();},2000);
				}else{
					var imageObj = $(new Image());
					imageObj.load({x: camposT1[0].x, y: camposT1[0].y}, function(e) {
						context.drawImage(this, e.data.x, e.data.y);
					}).attr('src', 'img/waterS.png');
				}
				break;
			case 1:
				
				break;
			case 2:
				
				break;
			case 3:
				
				break;
			case 4:
				
				break;
			case 5:
				
				break;
			case 6:
				break;
			case 7:
				
				break;
		}
    }
    
    function sendMessage(sender, receiver, message){
    	if (ws != null){
    		ws.send(JSON.stringify({messageInfo : {from : sender, to : receiver, message : message}}));
    	}
    }
    
    function disconnect() {
        if (ws != null) {
            ws.close();
            ws = null;
        }
        setConnected(false);
    }
    
    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        cleanConnectedUsers();
        if (connected) {
            updateUserConnected();
        } else {
            updateUserDisconnected();
        }
    }
    
    function updateUserConnected() {
        var inputUsername = $('#userName');
        var onLineUserName = $('.onLineUserName');
        onLineUserName.html(inputUsername.val());
        inputUsername.css({display:'none'});
        onLineUserName.css({visibility:'visible'});
        $('#status').html('Conectado');
        $('#status').attr({class : 'connected'});
        $('#onLineUsersPanel').css({visibility:'visible'});
        from=inputUsername.val();
        $('me').html(from);
    }

    function updateUserDisconnected() {
        $('.onLineUserName').css({visibility:'hidden'});
        $('#userName').css({display:''});
        $('#status').html('Desconectado');
        $('#status').attr({class : 'disconnected'});
        $('#onLineUsersPanel').css({visibility:'hidden'});
    }
    
    function cleanConnectedUsers() {
        $('#onlineUsers').html('');
    }
    
    /********* usuarios conectados *******/
    function addOnlineUser(userName) {
        var newOnlineUser = createOnlineUser(userName);
        newOnlineUser.appendTo($('#onlineUsers'));
        $('#onlineUsers li').click(function(){
        	if (!arePlaying){
        		opponent=$(this).text();
        		play(from,opponent,5);
        	}
    	});
    }

    function removeOnlineUser(userName) {
        $('#onlineUsers > li').each(function (index, elem) {
            if (elem.id == userName + 'onlineuser') {
                $(elem).remove();
            }
        });
    }

    function createOnlineUser(userName) {
        var link = $(document.createElement('a'));
        link.html(userName);        
        var li = $(document.createElement('li'));
        li.attr({id : (userName + 'onlineuser')});
        link.appendTo(li);
        return li;
    }
    
    function restartHotel(){
    	canvas = $('#tablero');
    	canvas.attr({width: cw * 2, height: ch});
    	canvasObject = canvas.get(0);
    	context = canvasObject.getContext("2d");
    	context.clearRect(0, 0, canvas.width, canvas.height);
    	drawBoard();
		initialize();
    }
    
    // metodos publicos
    return {
        connect : connect,
        disconnect : disconnect,
        sendMessage: sendMessage
    };
})();
